package com.birdboot.core;

import com.birdboot.annotation.Controller;
import com.birdboot.annotation.RequestMapping;
import com.birdboot.controller.UserController;
import com.birdboot.http.HttpServletRequest;
import com.birdboot.http.HttpServletResponse;
import jdk.nashorn.internal.objects.annotations.Constructor;

import javax.activation.MimetypesFileTypeMap;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

/**
 * 该类实际上是SpringMVC框架的一个核心类,用于与服务器(Tomcat)整合,接手处理请求的工作
 */
public class DispatcherServlet {
    private static DispatcherServlet instance = new DispatcherServlet();
    private static File baseDir;//类加载路径
    private static File staticDir;//类加载路径下的static目录

    static {
        try {
            baseDir = new File(
                    ClientHandler.class.getClassLoader().getResource(".").toURI()
            );
            staticDir = new File(baseDir, "static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    private DispatcherServlet() {
    }

    public static DispatcherServlet getInstance() {
        return instance;
    }

    public void service(HttpServletRequest request, HttpServletResponse response) {
        String path = request.getRequestURI();
        System.out.println("抽象路径:" + path);

        //首先判断请求路径是否为请求业务
        Method method = HandlerMapping.getMethod(path);
        if(method!=null){//如果根据请求路径提取到一个方法则说明本次为处理业务
            /*
                Method的方法:
                Class getDeclaringClass()
                可以获取该方法所属类的类对象
             */
            try {
                Class cls = method.getDeclaringClass();
                Object obj = cls.newInstance();
                method.invoke(obj,request,response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {//否则根据请求路径去处理静态资源
            File file = new File(staticDir, path);
            if (file.isFile()) {//file表示的是一个实际存在的文件
                response.setStatusCode(200);
                response.setStatusReason("OK");
                response.addHeader("Server", "BirdServer");
                response.setContentFile(file);
            } else {
                response.setStatusCode(404);
                response.setStatusReason("NotFound");
                file = new File(staticDir, "404.html");
                response.addHeader("Server", "BirdServer");
                response.setContentFile(file);
            }
        }
    }
}
